package net.sh.dpinfrastructure.support.global;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * 
 * 使用<a href="https://redis.io/">redis</a>来实现表id的自增
 * 
 * @version 1.0
 * @since JDK1.7
 * @author Lancer
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2017 SunTime Co'Ltd Inc. All rights reserved.
 * @date 2017年2月9日 下午7:46:33
 */
public class DPIDGenerateServiceUseRedis implements DPIDGenerateService {
    
    private JedisPool jedisPool;
    
    public static final String ID_GENERATER_NAMESPACE = "ID_BUILDER";
    
    public DPIDGenerateServiceUseRedis(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }
    
    /**
     * {@inheritDoc}<br>
     * 使用redis的<a href="https://redis.io/commands/incrby">incrby</a>命令来实现id单调递增
     */
    @Override
    public long getIncrementId(String tablename, long step) {
        if (StringUtils.isEmpty(tablename)) {
            throw new IllegalArgumentException("empty table name");
        }
        if (step < 1) {
            throw new IllegalArgumentException("step is less than 1");
        }
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.incrBy(ID_GENERATER_NAMESPACE + ":" + tablename, step);
        } finally {
            jedis.close();
        }
    }
    
    /**
     * {@inheritDoc}<br>
     * 使用<a href="https://redis.io">redis</a>的
     * <a href="https://redis.io/commands/incr">incr</a>
     * 命令来实现id单调递增
     */
    @Override
    public long getIncrementId(String tableName) {
        if (StringUtils.isEmpty(tableName)) {
            throw new IllegalArgumentException("empty tablename");
        }
        Jedis jedis = jedisPool.getResource();
        try {
            return jedis.incr(ID_GENERATER_NAMESPACE + ":" + tableName);
        } finally {
            jedis.close();
        }
    }
    
}
